<?php

declare(strict_types=1);

/**
 * @Author:     Frank
 * @contact     frank_hhm@163.com
 * @Date:       2022-11-15 16:07:50
 * @Last Modified time: 2022-11-18 23:01:51
 */
namespace app\common\model\system;

use app\common\enum\EnumFactory;
use frank\base\BaseModel;
use frank\traits\ModelTrait;

/**
 * 配置项模型
 * Class ConfigModel
 * @package app\common\model\system
 */
class ConfigModel extends BaseModel
{
    use ModelTrait;

    /**
     * 数据表主键
     */
    protected $pk = 'id';

    /**
     * 模型名称
     */
    protected $name = 'system_config';

    protected $append = ['options'];

    /**
     * 状态修改器
     */
    public function getStatusAttr($value)
    {
        return EnumFactory::instance('status')->getItem($value);
    }

    /**
     * 类型修改器
     */
    public function getTypeAttr($value)
    {
        return EnumFactory::instance('system.config.type')->getItem($value)?:$value;
    }

    /**
     * 表单类型修改器
     */
    public function getInputTypeAttr($value)
    {
        return EnumFactory::instance('system.config.input_type')->getItem($value)?:$value;
    }

    public function getValueAttr($value)
    {
        return is_numeric($value)?(int)$value:$value;
    }

    public function getOptionsAttr($value,$data){
        $options = [];
        if(!empty($data['parameter'])){
            $parameter = explode("\n", $data['parameter']);
            foreach ($parameter as $v) {
                if (strstr($v, '=>') !== false) {
                    $pdata = explode('=>', $v);
                    $options[] = ['label' => $pdata[1], 'value' => is_numeric($pdata[0])?(int)$pdata[0] : $pdata[0]];
                }
            }
        }
        return $options;
    }

    /**
     * 分类搜索器
     */
    public function searchConfigTabIdAttr($query, $value)
    {
        if(empty($value))  return $query;
        if (is_array($value)) {
            $query->whereIn('config_tab_id', $value);
        }else{
            $query->where('config_tab_id', $value);
        }
    }
}